// components/product/product-item/index.js
import componentBehavior from '../../../behaviors/component';
import { COMPONENT_OPTIONS } from '../../../constants/common';
import { getMaxNumber } from '../../../common/utils';

Component({
    behaviors: [componentBehavior],
    options: {
        ...COMPONENT_OPTIONS,
    },
    properties: {
        productInfo: {
            type: Object,
            value: {},
        },
        selectSku: {
            type: Object,
            value: null,
        },
        count: {
            type: Number,
            value: 0,
        },
        desc: {
            type: String,
            value: '',
        },
        minCount: {
            type: Number,
            value: 0,
        },
        noneHasStepper: {
            type: Boolean,
            value: true,
        },
    },
    observers: {
        'productInfo, selectSku': function (info, sku) {
            if (info && info.skus && info.skus.length) {
                const soldedQuantity = info.skus.reduce((s, c) => s + c.soldedQuantity, 0);
                this.setData({ soldedQuantity });
                if (!sku && info.skus.length === 1) {
                    sku = info.skus[0];
                }
                if (sku) {
                    const maxCount = sku && sku.maximum != -1 ? (sku.maximum - sku.freezeQuantity) : getMaxNumber();
                    this.setData({ maxCount });
                }
            }
        },
    },
    data: {
        maxCount: getMaxNumber(),
        soldedQuantity: 0,
    },
    methods: {
        handleClick(e) {
            const { productInfo } = this.data;
            this.triggerEvent('click', productInfo);
        },
        handleClickNum(e) {
            return;
        },
        handleChange(e) {
            const { productInfo } = this.data;
            productInfo.count = e.detail;
            this.triggerEvent('change', productInfo);
        },
        handlePlus() {
            const { productInfo } = this.data;
            productInfo.count = 1;
            this.triggerEvent('change', productInfo);
        },
    }
})

